package com.hmdp.service.impl;

import cn.hutool.Hutool;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.constant.MessageConstant;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.exception.LoginException;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import io.lettuce.core.BitFieldArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /*
    * 发送短信验证码
    * */
    @Override
    public void sendCode(String phone, HttpSession session) {
        //如果规范，生成验证码
        String code = RandomUtil.randomNumbers(6);

        //保存验证码到redis里面
        //session.setAttribute("code", code);
        stringRedisTemplate.opsForValue().
                set(RedisConstants.LOGIN_CODE_KEY + phone, code, RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);

        //发送验证码
        log.info("验证码保存成功，发送验证码{}", code);
    }

    /*
    * 登录功能
    * */
    @Override
    public Result login(LoginFormDTO loginFormDTO, HttpSession session) {
        // 校验手机号
        String phone = loginFormDTO.getPhone();
        if(RegexUtils.isPhoneInvalid(phone)){
            log.error("手机号格式不规范，抛出 LoginException"); // 添加日志
            return Result.error(MessageConstant.PHONE_IS_NOT_STANDARDIZED);
        }

        // 校验验证码
        String code = loginFormDTO.getCode();
        //从redis里面获取验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);
        if(!code.equals(cacheCode) || cacheCode.isEmpty()){
            // 不对直接报错
            return Result.error(MessageConstant.CODE_IS_INCORRECT);
        }

        //对就根据手机号到数据库里查找用户信息
        User user = query().eq("phone", phone).one();

        //用户不存在就新建用户
        if(user == null){
            user = createNewUser(phone);
            save(user);
        }

        //保存用户信息到session里
        //session.setAttribute("user", UserDTO);
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //保存用户信息到redis里面
        //1.1随机生成token，作为登录令牌
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String token = uuid.substring(0, 10);
        //1.2将用户信息保存到hash结构里面
        //userMap的转换问题：stringRedisTemplate只能允许string类型的key和value
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(), CopyOptions.create().
                setIgnoreNullValue(true).setFieldValueEditor((fileName, fileValue)-> fileValue.toString()));
        String tokenKey = RedisConstants.LOGIN_USER_KEY + token;
        //1.3存储
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);


        //1.4给token设置有效期
        stringRedisTemplate.expire(tokenKey, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        stringRedisTemplate.expire(tokenKey, 1000, TimeUnit.MINUTES);
        //1.5返回token
        return Result.success(token);
    }

    /**
     * 用户签到
     * @return
     */
    @Override
    public Result userSign() {
        // 1.获取当前登陆用户
        UserDTO user = UserHolder.getUser();
        if(user == null){
            return Result.error(MessageConstant.USER_IS_UNLOAD);
        }
        Long userId = user.getId();
        // 2.获取当天的日期并初始化
        LocalDateTime now = LocalDateTime.now();
        String nowDate = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        // 3.拼接key
        String key = RedisConstants.USER_SIGN_KEY + userId + nowDate;
        // 4.获取当天是当月的哪一天
        int dayOfMonth = now.getDayOfMonth();
        // 5.写入redis
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
        return Result.success();
    }

    /**
     * 统计用户当月连续签到次数
     * @return
     */
    @Override
    public Result userSignCount() {
        // 1.获取当前登陆用户
        UserDTO user = UserHolder.getUser();
        if(user == null){
            return Result.error(MessageConstant.USER_IS_UNLOAD);
        }
        Long userId = user.getId();
        // 2.获取当天的日期并初始化
        LocalDateTime now = LocalDateTime.now();
        String nowDate = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        // 3.拼接key
        String key = RedisConstants.USER_SIGN_KEY + userId + nowDate;
        // 4.获取当天是当月的哪一天
        int dayOfMonth = now.getDayOfMonth();
        // 5.从redis中获取当月的所有签到信息 BITFIELD key GET u[dayOfMonth] 0
        List<Long> bitField = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth))
                        .valueAt(0));
        // 5.1判断非空情况
        if (bitField == null || bitField.isEmpty()) {
            return Result.success(0);
        }
        // 5.2拿到get到的数字
        Long numOfSign = bitField.get(0);
        if (numOfSign == 0){
            return Result.success(0);
        }
        // 6.从最后一位向后循环遍历
        Integer count = 0;
        while (true){
            // 与1进行&运算
            long result = numOfSign & 1;
            if(result == 0){
                // 如果结果为0，结束循环
                break;
            }else{
                // 如果结果为1，计数器加一，并向后移动一位
                count++;
                numOfSign = numOfSign >> 1;
            }
        }
        // 7.返回计数器表示当月签到的次数
        return Result.success(count);
    }

    /**
     * 新建用户
     * @param phone
     * @return
     */
    private User createNewUser(String phone) {
        User user = new User();
        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setPhone(phone);
        return user;
    }
}
